package ledger

import (
	"testing"

	"git.cloud.inspur.com/ichain/ichain-protos-go/common"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/client/chain"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/client/iam"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/client/ledger"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/core/config"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/ichain_sdk"
	iam2 "git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/iam"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/test/data"
	"github.com/stretchr/testify/assert"
)

func blockIsValid(t *testing.T, block *common.Block) {
	assert.NotNil(t, block)
	assert.NotEmpty(t, block.GetData().GetData())
}

func TestLedger(t *testing.T) {
	env := data.GetEnvFromFlag()
	assert.NotNil(t, env)
	sdkCtx, err := ichain_sdk.New(config.FromBuilder(env.SdkBuilder()))
	defer sdkCtx.Close()
	assert.NoError(t, err)

	iamClient, err := iam.New(sdkCtx.Context())
	assert.NoError(t, err)
	identity, err := iamClient.CreateSigningIdentity(iam2.WithCert(env.ClientCert()), iam2.WithPrivateKey(env.ClientPvk()))
	assert.NoError(t, err)
	ledgerClient, err := ledger.New(sdkCtx.ChainContext(env.ChainId(), ichain_sdk.WithIdentity(identity)))
	assert.NoError(t, err)

	// 调用一次合约
	chainCli, err := chain.New(sdkCtx.ChainContext(env.ChainId(), ichain_sdk.WithIdentity(identity)))
	resp, err := chainCli.Execute(env.RandInvokeFunc())
	assert.NoError(t, err)
	txId := resp.TransactionID
	assert.NotEmpty(t, txId)

	block, err := ledgerClient.QueryBlockByTxID(txId)
	assert.NoError(t, err)
	blockIsValid(t, block)

	// 测试查询链配置接口
	chainCfg, err := ledgerClient.QueryConfig()
	assert.NoError(t, err)
	assert.NotEmpty(t, chainCfg)

	// 测试根据区块号查询区块接口
	block, err = ledgerClient.QueryBlock(block.GetHeader().GetNumber())
	assert.NoError(t, err)
	blockIsValid(t, block)

	// 测试查询配置区块
	cfgBlock, err := ledgerClient.QueryConfigBlock()
	assert.NoError(t, err)
	blockIsValid(t, cfgBlock)

	// 测试根据区块hash查询区块
	blockHash := block.GetHeader().GetPreviousHash()
	block, err = ledgerClient.QueryBlockByHash(blockHash)
	assert.NoErrorf(t, err, "hash is %s", string(blockHash))
	blockIsValid(t, block)

	// 根据交易id查询交易
	tx, err := ledgerClient.QueryTransaction(txId)
	assert.NoError(t, err, txId)
	assert.NotEmpty(t, tx)

}
